/*

  cone-search

  Copyright © 2010 - 2011 F.Hroch (hroch@physics.muni.cz)

  This file is part of Munipack.

  Munipack is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.
  
  Munipack is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
  
  You should have received a copy of the GNU General Public License
  along with Munipack.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "votable.h"
#include <wx/wx.h>
#include <wx/app.h>
#include <wx/url.h>
#include <wx/filesys.h>
#include <wx/wfstream.h>
#include <wx/txtstrm.h>
#include <wx/tokenzr.h>
#include <wx/fs_inet.h>
#include <list>

using namespace std;

class Cone: public wxAppConsole
{
public:

  bool OnInit();
  int OnRun();

private:

  int exitcode;

};

IMPLEMENT_APP_CONSOLE(Cone)


// consider a class - the same as in votable.cpp
wxString GetString(const wxString& line)
{
  list<wxString> items;

  wxStringTokenizer tb = wxStringTokenizer(line,"'",wxTOKEN_STRTOK);
  while ( tb.HasMoreTokens() ) {
    wxString x = tb.GetNextToken();
    items.push_back(x);
  }

  return items.back();
}



bool Cone::OnInit()
{
  wxString url, output, type, sort, ra, dec, sr = "SR=0.0167";
  list<wxString> pars;

  exitcode = 99;

  wxFFileInputStream istream(stdin);
  wxTextInputStream input(istream); 

  while(istream.IsOk() && ! istream.Eof()) {

    wxString line = input.ReadLine();
    wxLogDebug(line);

    if( line.StartsWith("RA") )
      ra = wxString("RA=") + GetString(line);

    if( line.StartsWith("DEC") )
      dec = wxString("DEC=") + GetString(line);

    if( line.StartsWith("SR") )
      sr = wxString("SR=") + GetString(line);

    if( line.StartsWith("URL") )
      url = GetString(line);

    if( line.StartsWith("OUTPUT") )
      output = GetString(line);

    if( line.StartsWith("TYPE") )
      type = GetString(line);

    if( line.StartsWith("SORT") )
      sort = GetString(line);

    if( line.StartsWith("PAR") )
      pars.push_back(GetString(line));
  }

  url += ra + wxString("&") + dec + wxString("&") + sr;

  for(list<wxString>::const_iterator a = pars.begin(); a != pars.end(); ++a)
    url += (a != pars.end() ? wxString("&") : wxString("")) + *a;

  wxLogDebug(url);

  wxURL u(url);
  VOTable vt(u);

  if( ! vt.IsOk() ) {
    exitcode = 6;
    wxPrintf("=CONE> Failed to open: `"+url+"'\n");
    return false;
  }

  if( ! sort.IsEmpty() )
    vt.Sort(sort);

  exitcode = vt.Save(output,type) ? 0 : 1;

  wxPrintf("=CONE> %d objects found\n",vt.RecordCount());

  return true;
}

int Cone::OnRun()
{
  wxLogDebug("OnRun: %d",exitcode);
  return exitcode;
}
